package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping({"/","index.html"})
    public String index(HttpServletRequest request){
        // 获取首页分类数据
        Result result = productFeignClient.getBaseCategoryList();
        request.setAttribute("list",result.getData());
        return "index/index";
    }

    // 使用静态页面进行渲染
    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex() throws IOException {

        // 获取数据
        Result baseCategoryList = productFeignClient.getBaseCategoryList();

        // 创建上下文
        Context context = new Context();
        context.setVariable("list",baseCategoryList.getData());

        File file = new File("D:\\index.html");
        FileWriter fileWriter = new FileWriter(file);

        templateEngine.process("index/index.html",context,fileWriter);

        return Result.ok();
    }

}
